package com.zoe.app.mybatisconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;


/**
 * @author Zoe.Zhang
 * @date 2021/10/16
 * @description
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.datasource.slave", name = "enable", havingValue = "true")
@MapperScan(basePackages = {"com.**.mapperslave"}, sqlSessionFactoryRef = "sqlSessionFactorySlave", sqlSessionTemplateRef = "sqlSessionTemplateSlave")
public class MyBatisConfigSlave {
    private static final Logger log = LoggerFactory.getLogger(MyBatisConfigSlave.class);
    @Autowired
    @Qualifier(value = "slave")
    private DataSource dataSource;

    @Bean
    SqlSessionFactory sqlSessionFactorySlave() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapperslave/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.zoe.app");
        log.info("从数据被加载");
        return sqlSessionFactoryBean.getObject();
    }


    @Bean
    SqlSessionTemplate sqlSessionTemplateSlave() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactorySlave());
    }
}
